package com.example.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.Utility.objIsNull;
import com.example.Utility.publicUtils;
import com.example.entity.Commodity;
import com.example.mapper.CommodityMapper;
import com.example.service.CommodityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Super
 */
@Slf4j
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CommodityMapper commodityMapper;

    /**
     * 评论对象
     *
     * @param CommodityObj commodity
     * @return Boolean
     */
    @PostMapping("/add")
    public Boolean add(@RequestBody Commodity commodity) {
        return commodityService.save(commodity);
    }


    /**
     * 获取指定id评论内容
     *
     * @param commodityId 商品id
     * @return List<Commodity>
     */
    @RequestMapping(value = ("/getCommodityList"), method = RequestMethod.GET)
    public List<Commodity> getCommodityList(Long commodityId) {
        try {
            if (objIsNull.isNull(commodityId)) {
                throw new IllegalArgumentException("商品id不存在");
            }
            LambdaQueryWrapper<Commodity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Commodity::getCommodityId, commodityId);
            return commodityMapper.selectList(queryWrapper).stream()
                    .map(key -> {
                        key.setImageList(JSONArray.parseArray(key.getImage()));
                        key.setPageTime(publicUtils.getTimes("-"));
                        return key;
                    })
                    .collect(Collectors.toList());
        } catch (Exception ExceptionMsg) {
            log.error(String.format("获取商品列表信息失败：%S", ExceptionMsg));
            return Collections.emptyList();
        }
    }
}
